﻿using System;
using RestSharp;
using RestSharp.Contrib;
using Web.Core.EventArgs;
using Newtonsoft.Json.Linq;
using Web.Core.Extensions;
using Ayatta.Contract.Domain;
using Web.Core.Models.Game;
using Ayatta.Common.Extension;
using System.Collections.Specialized;

namespace Web.Core.GameProxys
{
    /// <summary>
    /// 九龙潮
    /// </summary>
    internal sealed class JlcGameClient : GameClient
    {
        private const string RechargeKey = "NqM9QFsrRoK2m7SNpK5zRpEa5r8p9Qm4";

        public JlcGameClient(int gameId)
            : base(gameId)
        {
            Client.BaseUrl = BaseUrl = "http://api.9lc.ouere.com";
            DefaultKey = "RZCQFllOumhKVq8ewSXjVWVSfqvlAYd5";
        }

        /// <summary>
        /// 获取登录url
        /// </summary>
        /// <param name="guid">用户GUID</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public override string GetLoginUri(string guid, params string[] param)
        {
            var sid = param[0] ?? string.Empty;

            var auth = GetAuth(guid, sid);
            var sign = (auth + DefaultKey).HashPassword().ToLower();

            var nv = new NameValueCollection();
            nv.Add("auth", auth);
            nv.Add("sign", sign);

            const string url = "http://res.9.game2.com.cn/indexouere.html";
            return url + nv.ToQueryString(true, false, true);
        }

        /// <summary>
        /// 检查用户是否创建角色
        /// </summary>
        /// <param name="guid">用户GUID</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public override MagicKit<string> CheckUser(string guid, params string[] param)
        {
            var result = new MagicKit<string>();

            var sid = param[0] ?? string.Empty;
            var time = GetUnixTime();
            var sign = (sid + guid + time + RechargeKey).HashPassword().ToLower();

            var request = new RestRequest("getUserRole.php");
            request.Timeout = Timeout;
            request.AddParameter("sid", sid);
            request.AddParameter("uid", guid);
            request.AddParameter("time", time);
            request.AddParameter("sign", sign);
            try
            {
                var content = Client.Execute(request).Content;
                var json = JObject.Parse(content);
                var status = json.Value<string>("result") == "1";
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = content;
                }
            }
            catch (Exception e)
            {
                result.Message = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="guid">用户GUID</param>
        /// <param name="serverId">游戏区服Id</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public override MagicKit<UserInfo> GetUser(string guid, int serverId, params string[] param)
        {
            var result = new MagicKit<UserInfo>();
            var user = new UserInfo(guid) { GameId = GameId, ServerId = serverId };

            var sid = param[0] ?? string.Empty;
            var time = GetUnixTime();
            var sign = (sid + guid + time + RechargeKey).HashPassword().ToLower();

            var request = new RestRequest("getUserRole.php");
            request.Timeout = Timeout;
            request.AddParameter("sid", sid);
            request.AddParameter("uid", guid);
            request.AddParameter("time", time);
            request.AddParameter("sign", sign);
            try
            {
                var content = Client.Execute(request).Content;
                if (!string.IsNullOrEmpty(content))
                {
                    var json = JObject.Parse(content.Replace("[]", "null"));
                    var status = result.Status = json.Value<string>("result") == "1";
                    if (status)
                    {
                        var data = json["roleinfo"];
                        if (data.HasValues)
                        {
                            var name = data[0]["name"].Value<string>();
                            var level = data[0]["grade"].Value<int>();
                            user.RoleName = HttpUtility.UrlDecode(name);
                            user.Level = level;
                            user.ModifiedOn = DateTime.Now;
                            OnUpdated(new EventArgs<UserInfo>(user));
                            result.Data = user;
                        }
                        else
                        {
                            user.RoleName = string.Empty;
                            user.Level = 0;
                        }
                    }
                    else
                    {
                        result.Message = content;
                    }
                }
            }
            catch (Exception e)
            {
                result.Message = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="guid">用户GUID</param>
        /// <param name="order">订单</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public override MagicKit<OrderInfo> Recharge(string guid, OrderInfo order, params string[] param)
        {
            var result = new MagicKit<OrderInfo>();
            var time = GetUnixTime();
            var sid = param[0] ?? string.Empty;
            var moeny = order.Amount.ToString("F1");
            var gold = (order.Amount * 10).ToString("F0");

            var nv = new NameValueCollection();
            nv.Add("sid", sid);
            nv.Add("uid", guid);
            nv.Add("oid", order.Id);
            nv.Add("money", moeny);
            nv.Add("gold", gold);
            nv.Add("time", time);

            var sign = (nv.ToQueryString() + RechargeKey).HashPassword().ToLower();

            var request = new RestRequest("pay.php");
            request.Timeout = Timeout;

            request.AddParameter("sid", sid);
            request.AddParameter("uid", guid);
            request.AddParameter("oid", order.Id);
            request.AddParameter("money", moeny);
            request.AddParameter("gold", gold);
            request.AddParameter("time", time);
            request.AddParameter("sign", sign);

            try
            {
                order.Extra = Client.BuildUri(request).ToString();
                var content = Client.Execute(request).Content;
                var status = content.Trim() == "1";
                if (status)
                {
                    result.Status = true;
                    OnRecharged(new EventArgs<OrderInfo>(order));
                }
                else
                {
                    result.Message = content;
                }
            }
            catch (Exception e)
            {
                result.Message = e.Message;
            }
            return result;
        }

        private static string GetAuth(string uid, string sid)
        {
            var param = new NameValueCollection();
            var time = GetUnixTime();
            param.Add("sid", sid);
            param.Add("uid", uid);
            param.Add("time", time);
            param.Add("indulge", "n");
            return param.ToQueryString().ToBase64String();
        }
    }
}